package com.chungkui.bond.authmanager.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chungkui.bond.authmanager.bean.Router;
import com.chungkui.bond.authmanager.mapper.RouterMapper;
import com.chungkui.bond.authmanager.service.RouterService;
import com.chungkui.bond.authmanager.utils.MenuUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Service
public class RouterServiceImpl extends ServiceImpl<RouterMapper, Router> implements RouterService {
    @Override
    public List<Router> listAll2tree(String clientId) {
        return formatTree(this.baseMapper.listWithPermission(clientId));
    }

    @Override
    public List<Router> listByRoles2tree(Set<String> roles, String clientId) {
        List<Router> list = this.listByRole(roles, clientId);
        return formatTree(list);
    }


    @Override
    public List<Router> buildMenuByRoles(Set<String> roles, String clientId) {
        List<Router> list = listByRole(roles, clientId);
        return MenuUtil.buildMenuByRouters(formatTree(list));
    }


    private List<Router> listByRole(Set<String> role, String clientId) {
        if (role != null && !role.isEmpty()) {

            return this.baseMapper.listByRole(role, clientId);
        }
        return new ArrayList<>();
    }

    private List<Router> formatTree(List<Router> datalist) {
        Iterator<Router> iterator = datalist.iterator();
        List<Router> topRouter = new ArrayList<Router>();
        while (iterator.hasNext()) {
            Router s = iterator.next();
            //去掉级联关系后需要手动维护这个属性
            boolean getParent = false;
            for (Router p : datalist) {
                if (p.getId().equals(s.getParentId())) {
                    List sunList = p.getChildren();
                    if (sunList == null) {
                        p.setChildren(new ArrayList());
                    }
                    p.getChildren().add(s);
                    getParent = true;
                    break;
                }
            }
            if (!getParent) {
                topRouter.add(s);
            }

        }
        return topRouter;
    }

}
